package na.learn.java.threads;

public class Worker implements Runnable {
	private static int count = 0;

	public Worker(ResourcePool resourcePool) {
		this.resourcePool = resourcePool;
	}

	private ResourcePool resourcePool;

	public void run() {
		while (true) {
			produce();
			consume();
		}

	}

	protected synchronized void produce() {

		try {
			while (resourcePool.getResource() != null) {
				wait();
			}

			resourcePool.setResource("count" + (++count));
			System.out.println("Worker thread " + Thread.currentThread().getName()
					+ " setting Resource " + resourcePool.getResource());
			Thread.sleep(2111);
			notify();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	protected synchronized void consume() {

		try {
			while (resourcePool.getResource() == null) {
				wait();
			}
			System.out.println("Consumer thread " + Thread.currentThread().getName()
					+ " got Resource " + resourcePool.getResource());
			// Thread.sleep(2000);
			resourcePool.setResource(null);
			notify();
		} catch (InterruptedException e) {

			e.printStackTrace();
		}

	}

	public ResourcePool getResourcePool() {
		return resourcePool;
	}

	public void setResourcePool(ResourcePool resourcePool) {
		this.resourcePool = resourcePool;
	}

}
